package com.starblink.android.basic.urllink

import android.app.Activity
import android.net.Uri
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.navigateUri
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.log.YYLogUtils

/**
 * 应用内部拉起指定界面
 */
object PullUpPageUtils {


    /**********************************应用内解析跳转*************************************************/


    /**
     * 入口1
     */
    fun routeForPush(context: Activity, url: String = "", offCur: Boolean = false) {
        if (url.startsWith(UriLinkConfig.HTTP_PRO_STR) || url.startsWith(UriLinkConfig.HTTPS_PRO_STR)) {
            context.navigationTo(url = url, params = {
                withString("withSpm", "1")
            })
        } else {
            routePageIntercept4Url(context, url = url, offCur = offCur)
        }
    }


    /**
     * https://starblink.feishu.cn/wiki/wikcntU54hs7hZLViPSbLS0jpFc
     * 入口2
     * @param externalPull 是不是外链拉起的APP
     * 命令行
     * adb shell
     *
     * am start "getguang://guang/home_camera?a1=aaa" com.starblink.android.guang
    am start "https://applink.getguang.com/openApp" com.starblink.android.guang
    am start "https://applink.getguang.com/openApp?target_url=http://www.baidu.com" com.starblink.android.guang
    am start "getguang://guang/h5?a1=aaa&url=http://www.baidu.com" com.starblink.android.guang
     */
    fun routePageIntercept4Url(
        activity: Activity,
        url: String = "",
        offCur: Boolean = false,
        externalPull: Boolean = false
    ) {
        //外链拉起的APP
        if (externalPull) {
            if (url.startsWith(UriLinkConfig.SCHEME_GUANG)) {
                getGuangIntercept(activity, url, offCur = offCur)
            } else if (url.startsWith(UriLinkConfig.HTTP_STR)) {
                handleUniversalLink(activity = activity, universalLink = url)
            }
        } else {
            //内部跳转
            getGuangIntercept(activity, url, offCur = offCur);
        }
    }

    ///这里处理点击通知栏 由scheme协议拉起指定界面的业务
    private fun getGuangIntercept(activity: Activity, url: String, offCur: Boolean = false) {
        val uri = Uri.parse(url)
        YYLogUtils.e("----handleSchemeOrDeepLink---${uri}----，  ${uri.path}")
        if (needLoginState(uri)) {
            LoginCheckInterceptor.check2Login(activity) {
                handleRoute(
                    activity = activity,
                    uri = uri,
                    offCur = offCur
                )
            }
        } else {
            handleRoute(
                activity = activity,
                uri = uri,
                offCur = offCur
            )
        }
    }

    //原flutter迁移
    private fun handleUniversalLink(activity: Activity, universalLink: String) {
        if (universalLink.isNotBlank()) {
            var link = Uri.parse(universalLink)
            //如果没有targetUrl 不跳转
            var targetUrl = link.getQueryParameter("target_url")
            if (targetUrl.isNullOrBlank()) {
                return
            }
            getGuangIntercept(activity, targetUrl, offCur = false)
        }
    }

    /**
     * @param offCur 是否关闭当前界面再跳转
     */
    private fun handleRoute(activity: Activity, uri: Uri, offCur: Boolean = false) {
        if ("/home" == uri.path) {
            //跳转至首页（MainActivity），MainActivity是singleTask，会回调首页的onNewIntent()
            navigateUri(uri)
        } else {
            if (offCur) {
                navigateUri(uri)
                activity.finish()
            } else {
                navigateUri(uri)
            }
        }
    }

    //原flutter迁移
    private fun needLoginState(uri: Uri): Boolean {
        return uri.getQueryParameter("n_l") == "y"
    }

    //原flutter迁移
    private fun traceEmailOpenApp(uri: Uri) {
        if (uri.getQueryParameter("source") == "email") {

            //如果是从邮箱打开 那么埋点
            //TODO
//            SKAnalytics.trace2(
//                ReportModel(eventId: EventId. id_226, eventSite: EventScene. email));
//            SKTracker().commonTrack(
//                event: TrackEvent. elementClick,
//            pageName: '',
//            elementName: 'TraceEmailOpenApp',
//            );
        }
    }


    fun h5Url(h5SubUrl: String): String {
        var url = h5SubUrl
        while (url.startsWith("/")) {
            url = url.substring(1)
        }
        return "${BaseApiClient.getCurrSvrCfgEnvH5Host()}$url"
    }

    /**
     * 字符串转参数
     */
    fun parseParams(paramsStr: String): HashMap<String, String> {
        val urlParams = paramsStr.split("&")
        val result = hashMapOf<String, String>()
        urlParams.forEach {
            val param = it.split("=")
            if (param.size == 2) {
                result[param[0]] = param[1]
            }
        }
        return result
    }

    fun getShareBaseUrl(): String {
        val host = BaseApiClient.getCurrSvrCfgEnvHost()
        val envName = BaseApiClient.getCurrSvrCfgEnvName()
        return "$host/share/#$envName."
    }

}